// 角色管理
remanApp.controller("roleCtrl", function($scope, $http, $modal,$compile,$state){
	$scope.pageSize = 15;//默认初始值
	$scope.totalPage = 0;//总页码
	$scope.pageNow = 1;//当前页码
	$scope.totalRow = 0;//总数量
	$scope.sort="";//排序字段
	$scope.order="";//排序方式
	$scope.search="";//搜索字段
	$scope.pageNumList = [];//分页页码
	$scope.pageList=[10,15,20,50,100,200];//设置分页数的列表
	
	
	$scope.useBatchStatus=false;//默认隐藏批处理按钮
	$scope.useBatchSave=false;//批量保存状态
	$scope.addRoleIndex = [];
	$scope.roleList = [];//权限数据集合

	
	$scope.tab = 1;//默认选项卡
	$scope.isSelected = function(setTab){
		return $scope.tab === setTab;
	};
	
	//表格数据源初始化
	$scope.init=function(){
		$scope.totalPage = 0;//总页码
		$scope.pageNow = 1;//当前页码
		$scope.totalRow = 0;//总数量
		$scope.useBatchStatus=false;//默认隐藏批处理按钮
		$scope.checkBatchSave();//检测批量添加按钮
		$scope.search=$("#search").parent().prev().val();//重新检搜索字段
		$scope.loadList($scope.pageNow, $scope.pageSize,$scope.sort,$scope.order,$scope.search);
	}
	
	// 查询全部记录数据
	$scope.loadList = function(pageNow, pageSize,sort,order,search){
		var layerId = layer.load(1);
		var params={"pageNow":pageNow,"pageSize":pageSize,"sort":sort,"order":order,"search":search};
		$http.post(WEBROOT + "/role/getData.do",params)
		.success(function(data, status){
			if(data.errcode!=0){
				layer.alert(data.msg,{icon:0});
			} else {
				$scope.totalRow = data.result.totalRow;
				$scope.totalPage = data.result.totalPage;
				$scope.roleList = data.result.list;
				$scope.pageNumList=data.result.pageNumList;
			}
			layer.close(layerId);
		}).error(function(data, status){});
	};
	//排序
	$scope.sortFun=function(event){
		var clas=$(event.target).attr("class");//获取当前点击的样式
		$scope.sort=$(event.target).attr("data-sort");//排序字段
		$scope.order="asc";//排序方式
		$(event.target).parent().parent().parent().find("th>div>a").attr("class","header");
		if(clas==="header"){
			$(event.target).attr("class","headerSortDown");
			$scope.order="asc";
		}else if(clas==="headerSortDown"){
			$(event.target).attr("class","headerSortUp");
			$scope.order="desc";
		}else{
			$(event.target).attr("class","headerSortDown");
			$scope.order="asc";
		}
		//重新加载数据
		$scope.init();
	};
	// 改变页数
	$scope.changePage = function(page, offset){
		page = page + offset;
		if($scope.pageNow != page){
			$scope.pageNow = page;
			$scope.loadList(page, $scope.pageSize,$scope.sort,$scope.order,$scope.search);
		}
	};
	//改变每页显示量
	$scope.pageSizeSelectChange = function(pageSize){
		//还原为默认值
		$scope.pageSize = pageSize;
		$scope.init();
	};
	
	// 判断是否第1页
	$scope.isFirst = function(){
		return $scope.pageNow == 1;
	};
	// 判断是否未页
	$scope.isLast = function(){
		return $scope.totalPage == $scope.pageNow;
	};
	// 判断是否当前页
	$scope.isCurrent = function(page){
		return $scope.pageNow == page;
	};

	//全选
	$scope.checkAll = function(event){
		if(event!=null){
			$('#data-list>tbody>tr>td>input[type="checkbox"]').prop("checked", $(event.target).is(":checked"));
			if($('#data-list>tbody>tr>td>input[type="checkbox"]:checked').size() > 1){
				$scope.useBatchStatus = true;
			} else {
				$scope.useBatchStatus = false;
			}
		}else{
			$('#data-list>tbody>tr>td>input[type="checkbox"]').prop("checked",true);
			
			if($('#data-list>tbody>tr>td>input[type="checkbox"]:checked').size() > 1){
				$scope.useBatchStatus = true;
			} else {
				$scope.useBatchStatus = false;
			}
		}
	};
	//反选
	$scope.reverse = function(){
		//获取当前行复选框是否选中再取反向选择
		$('#data-list>tbody>tr>td>input[type="checkbox"]').each(function(i){
			$(this).prop("checked",!$(this).prop("checked"))
		});
		
		if($('#data-list>tbody>tr>td>input[type="checkbox"]:checked').size() > 1){
			$scope.useBatchStatus = true;
		} else {
			$scope.useBatchStatus = false;
		}
	};
	// 检测是否显示隐藏按钮
	$scope.checkSelect = function(){
		if($('#data-list>tbody>tr>td>input[type="checkbox"]:checked').size() > 1){
			$scope.useBatchStatus = true;
		} else {
			$scope.useBatchStatus = false;
		}
	};
	//增强点击行选中
	$scope.hitRow = function(event){
		var obj=event.target;
		var item=$(obj).parent().children("td").first().children("input[type='checkbox']");
		item.prop("checked",!item.prop("checked"));
		//检测是否显示隐藏按钮
		$scope.checkSelect();
	};
	
	//删除
	$scope.del = function(event){
		var ids = [];
		if(event!=null){
			var id=$(event.target).parent().parent().attr("id");
			ids.push(id);
		}else{
			$('#data-list tbody>tr>td>input[type="checkbox"]:checked').each(function(index){
				ids.push($(this).parent().parent().attr("id"));
			});
		}
		//删除
		if(ids.length != 0){
			layer.confirm('确认是否删除？', {
			    btn: ['确认','取消'] //按钮
			}, function(){
				var layerId = layer.load(1);
				$http.post(WEBROOT + "/role/del.do", {"ids":ids.join(",")})
				.success(function(data, status){
					if(data.errcode!=0){
						layer.alert(data.msg,{icon:0});
					} else {
						layer.msg('删除成功', {icon: 1});
						$scope.init();
					}
					layer.close(layerId);
				}).error(function(data, status){});
			}, function(){
			    
			});
		}
	};
	
	//增加行
	$scope.addRow = function(){
		var index = $scope.addRoleIndex.length;
		$scope.addRoleIndex.push(index);
		
		$("#data-list tbody").prepend($compile($("#data-list tbody .addRow:hidden").clone().attr("index",index).removeClass("hide").addClass("roleRow").addClass("text-center").get(0))($scope));
		
		$scope.checkBatchSave();
	};
	
	//检测批量保存按钮
	$scope.checkBatchSave = function(){
		if($("#data-list tbody .addRow").size() > 2){
			$scope.useBatchSave = true;
		}else if($("#data-list tbody .addRow").size() < 3){
			$scope.useBatchSave = false;
		}
	}
	
	//取消新增行
	$scope.cancelAdd = function(event){
		$(event.target).parent().parent().remove();
		$scope.checkBatchSave();
	};
	//保存
	$scope.saveBtn = function(event){
		var role = $scope.formatRoleData($(event.target).parent().parent());
		if(role){
			$scope.save([role]);
		}
	};
	//批量保存
	$scope.batchSave = function(event){
		var roles = [];
		$("#data-list tbody .addRow:visible").each(function(){
			var item=$scope.formatRoleData($(this));
			if(item){
				roles.push(item);
			}
		});
		if(roles.length > 0){
			$scope.save(roles);
		}
	};
	// 格式化行
	$scope.formatRoleData = function(obj){
		var index=obj.attr("index");
		var role_name = obj.find("input[name='role_name']").val();
		var coding = obj.find("input[name='coding']").val();
		var seq = obj.find("input[name='seq']").val();
		
		if(checkNullAlt(obj.find("input[name='role_name']"), "角色名") && checkNullAlt(obj.find("input[name='coding']"), "角色编码")){
			var roleStr = '{"index":"'+index+'","role_name":"'+role_name+'","coding":"'+coding+'","seq":"'+seq+'"}';
			return roleStr;
		} else {
			return false;
		}
	};
	// 保存角色
	$scope.save = function(roles){
		if(roles.length > 0){
			var layerId = layer.load(1);
			$.ajax({
				url : WEBROOT + "/role/save.do",
				type : "POST",
				data : "roles=["+roles+"]",
				success : function(data) {
					layer.close(layerId);
					if(data.errcode!=0){
						layer.alert(data.msg,{icon:0});
					}else{
						for(var i=0; i<data.result.addRoleIndex.length; i++){
							$("#data-list tbody .addRow[index='"+data.result.addRoleIndex[i]+"']").remove();
						}
						layer.msg("保存成功", {icon:1});
						$scope.init();
					}
				}
			});
		}
	};
	
	//编辑
	$scope.editorBtn = function(obj){
		//将其他修改行还原
		var canelTr = $("#data-list tbody .role-upt");
		canelTr.each(function(){
			var id = canelTr.attr("id");
			$scope.cancelEditor(id);
		}); 
		
		var id = obj.role.id;
		var role_name = obj.role.role_name;
		var coding = obj.role.coding;
		var seq = obj.role.seq;
		var ctime=obj.role.ctime;
		
		var item = $("#data-list tbody .updateRow:hidden").clone().removeClass("hide");
		item.find("td>a").eq(0).attr('ng-click',"editor('"+id+"')");
		item.find("td>a").eq(1).attr('ng-click',"cancelEditor('"+id+"')");
		item = $compile(item.get(0))($scope);
		
		item.attr("id",id).addClass("role-upt");
		item.find("td>input[name='role_name']").val(role_name);
		item.find("td>input[name='coding']").val(coding);
		item.find("td>input[name='seq']").val(seq);
		item.find("td>input[name='ctime']").val(ctime);
		var tr = $("#data-list tr#"+id);
		tr.after(item);
		tr.attr("id",id+"_bak").addClass("hide");
	};
	// 取消修改记录
	$scope.cancelEditor = function(id){
		var tr = $("#data-list tr#"+id+"_bak");
		var trUpt = $("#data-list tr#"+id);
		trUpt.remove();
		tr.removeClass("hide").attr("id",id);
	};
	//修改
	$scope.editor = function(id){
		var trUpt = $("#data-list tr#"+id);
		var data = $scope.formatRoleData(trUpt);
		var item=JSON.parse(data);
		delete item.index;
		item.id=id;
		var layerId = layer.load(1);
		$http.post(WEBROOT + "/role/editor.do",item)
		.success(function(data, status){
			if(data.errcode!=0){
				layer.alert(data.msg,{icon:0});
			} else {
				layer.msg("修改成功",{icon:1});
				$scope.init();
			}
			layer.close(layerId);
		}).error(function(data, status){});
	};
});

remanApp.controller("rolePowerCtrl", function($scope, $http, $modal,$compile,$stateParams,$state){	
	var tree;
	if($stateParams.id){
		$scope.initRolePower = function(){
			var id=$stateParams.id;
			var layerId = layer.load(1);
			$http.post(WEBROOT + "/role/findById.do", "id="+id)
			.success(function(data, status){
				if(data.errcode!=0){
					layer.alert(data.msg,{icon:0});
				} else {
					$scope.id=data.result.role.id;
					$scope.coding=data.result.role.coding;
					$scope.role_name=data.result.role.role_name;
					$scope.seq=data.result.role.seq;
				}
				layer.close(layerId);
			}).error(function(data, status){});
			
			$.post(WEBROOT + "/power/getTreeAllData.do","id="+id,function(data){
				if(data.errcode==0){//操作成功
					tree = $.fn.zTree.init($("#treeRolePower"),{
						check : {
							enable : true,
							chkStyle : "checkbox",
							chkboxType : {
								"Y" : "ps",
								"N" : "ps"
							}
						},
						data : {// 数据字段属性等设置
							simpleData : {
								enable : true,
								idKey : "id",
								pIdKey : "father_id",
								rootPId:"1"
							},
							key : {
								checked : "checked",
								name : "power_name",
								url : ""
							}
						}
					},data.result.list);
				}else{
					
				}
			},"JSON");
		}
	};
	
		$scope.saveAuth = function(){
			var nodes = tree.getCheckedNodes(true);
			var ids="";
			for(var i=0;i<nodes.length;i++){
				ids=ids+","+nodes[i].id;
			}
			ids=ids.substr(1,ids.length-1);//获取选中的id集合
			$.post(WEBROOT+"/role/saveAuth.do","ids="+ids+"&role_id="+$scope.id,function(data){
				if(data.errcode!=0){
					layer.alert(data.msg,{icon:0});
				} else {
					layer.msg("授权成功",{icon:1});
					$state.go('role');
				}
			},"JSON");
		};
});